import React, { useEffect, useState } from 'react';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  TeamOutlined,
  SearchOutlined,
  SyncOutlined,
  BellOutlined,
  ShopOutlined,
  UserOutlined,
  BarsOutlined,
  InstagramOutlined,
} from '@ant-design/icons';

import { Button, Layout, Menu, theme, Breadcrumb } from 'antd';
import type { MenuProps } from 'antd';
import { NavLink, NavLinkRenderProps, Outlet} from 'react-router-dom';
import { homeItem } from '../../unit/type';
import { RouterChildren } from '../../router/router'
import './home.scss'
// 引组件
import Title from '../../components/title/title'
// 引仓库标签栏
import { TabColor } from '../../store/color/them'
import { useSelector } from 'react-redux';
import { changeTagColor } from '../../store/color/them'
// 标签栏
import { CloseCircleOutlined } from '@ant-design/icons';
import { Tag } from 'antd';



function index() {
  const { Header, Sider, Content, Footer } = Layout;
  type MenuItem = Required<MenuProps>['items'][number];
  function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
  ): MenuItem {
    return {
      key,
      icon,
      children,
      label,
    } as MenuItem;
  }

  function setIcon(src: any) {
    switch (src) {
      case "TeamOutlined":
        return <TeamOutlined />
      case "SearchOutlined":
        return <SearchOutlined />
      case "SyncOutlined":
        return <SyncOutlined />
      case "BellOutlined":
        return <BellOutlined />

      case "ShopOutlined":
        return <ShopOutlined />
      case "UserOutlined":
        return <UserOutlined />
      case "BarsOutlined":
        return <BarsOutlined />
      case "InstagramOutlined":
        return <InstagramOutlined />
    }
  }

  // 循环渲染
  const renderHome = (arr: homeItem[]) => {
    const items: any = []
    arr && arr.forEach((item, index) => {
      items.push(getItem(<NavLink to={item.path}>{item.title}</NavLink>, item.id,
        setIcon(item.icon), item.children && renderHome(item.children)))
    })
    return items
  }

  // 面包屑 菜单数据
  const [menuData, setMenuData] = useState(RouterChildren);

  // 取面包屑数据
  let menu = localStorage.getItem('menuData');
  // console.log(menu, 'menu');


  if (menu) {
    menu = JSON.parse(menu);

  }
  //面包屑数据
  const [breadcrumb, setBreadcrumb] = useState<any>(menu || [
    { title: '首页', href: '/home/index' },
  ])

  //面包屑
  const [collapsed, setCollapsed] = useState(false);
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();


  //扁平化菜单数据
  function flattenRoutes(routes: any[]) {
    let result: any[] = [];
    function flatten(route: { children: any[]; }) {
      // 添加当前路由到结果数组  
      result.push(route);
      // 如果存在子路由，则递归扁平化子路由  
      if (route.children && route.children.length > 0) {
        route.children.forEach((child: any) => flatten(child));
      }
    }
    // 遍历传入的路由数组并扁平化  
    routes.forEach((route: any) => flatten(route));

    return result;
  }
  const flattenedRoutes = flattenRoutes(menuData);
  // setMenuList(flattenedRoutes)
  console.log(flattenedRoutes, '扁平')
  // 渲染点击过的扁平化数据  按钮
  const [btnarr, setbtnarr] = useState([flattenedRoutes[0]])
  //点击跳转
  // console.log(menuData, 'bbb');
  const chngeClick = (e: any) => {
    console.log(e.keyPath, 'key点击后')
    let arr = flattenedRoutes.filter(item => e.keyPath.includes(item.id))
    // console.log(arr, '筛选后')
    let newArr = arr.map((item, index) => {
      return {
        title: item.title,
        href: item.path
      }
    });
    // 存面包屑数据
    localStorage.setItem('menuData', JSON.stringify(newArr));
    // console.log(newArr, '0000000000000')
    setBreadcrumb(JSON.parse(JSON.stringify(newArr)))

    let aa = flattenedRoutes.filter(item => e.keyPath.includes(item.id))
    // let bb=[...new Set(aa)]
    setbtnarr([...new Set(btnarr.concat(...aa))])
    // console.log(bb,'过滤后tag')
  }

  // 开关
  let [theme1, setTheme] = useState('dark')
  function setMyThmem(flag: boolean) {
    // console.log(flag, 'flag')
    flag == true ? setTheme('dark') : setTheme('light')
  }
  let [flag, setFlag] = useState(false)
  function setMyTab(e: boolean) {
    setFlag(e)
    // setMyTheme(flag)
  }
  // console.log(flag);





  // 标签栏显示
  const themeConfig = useSelector((state: TabColor) => state.themeSlice)
  // console.log(themeConfig, 'themeConfig');
  const changeTagColor = useSelector((state: changeTagColor) => state.themeSlice)

  return (
    <Layout style={{ minHeight: '100vh' }}>
      {/* 面包屑 */}
      <Sider trigger={null} collapsible theme={theme1} collapsed={collapsed} onCollapse={(value) => setCollapsed(value)}>
        <div className="demo-logo-vertical" />
        <Menu
          // theme='dark'
          theme={theme1}
          mode="inline"
          defaultSelectedKeys={['1']}
          items={renderHome(RouterChildren)}
          onClick={chngeClick}
        // onClick={changclick}
        />
      </Sider>
      <Layout>
        <Header style={{ padding: 0, background: changeTagColor.tabColor }} className='menuheader'>
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{
              fontSize: '16px',
              width: 64,
              height: 64,
            }}

          />
          <span className='headerBox'>
            {/* 面包屑 */}
            <Breadcrumb items={breadcrumb} style={{ display: 'inline-block' }} />
            <Title setMyThmem={setMyThmem} setMyTab={setMyTab}></Title>
          </span>
        </Header>
        {/* 导航栏 */}
        <div className="breadcrumb"  style={{ display: themeConfig.istags ? 'block' : 'none' }}>
          {/* 面包屑 */}
          {
            btnarr && btnarr.map((item, index) => {
              return <span>
                <Tag closeIcon={<CloseCircleOutlined />}> <NavLink to={item.path}>{item.title}</NavLink>
                </Tag>
              </span>
            })
          }


        </div>
        <Content style={{ margin: '0 16px' }}>
          <div
            style={{
              padding: 24,
              minHeight: 360,
              background: colorBgContainer,
              borderRadius: borderRadiusLG,
            }}
          >
            <Outlet></Outlet>
          </div>
        </Content>
      </Layout>
    </Layout>
  )
}

export default index
